package DictData;

import java.io.DataOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import BufferReader.BufferReader;

public class BaseDictData{

	public static final String EndLine = "\r\n";
	public static int MaxItemSize = 8;
	
	protected String items[] = null;
	protected byte itemsFlag = 0;
	protected ArrayList<BaseDictData> groups = null;
	
	public BaseDictData(){
		items = new String[MaxItemSize];
	}
	
	public BaseDictData(int itemsSize){
		items = new String[itemsSize];
	}
	
	protected void Export(FileWriter writer) throws IOException{
		if(groups != null){
			for(BaseDictData group : groups){
				group.Export(writer);
			}
		}
		writer.write(EndLine);
		writer.flush();
	}

	public void SetItem(int id, String content){
		items[id] = content;
		itemsFlag |= 0x01 << id;
	}
	
	public void AddGroup(BaseDictData newGroup){
		if(groups == null){
			groups = new ArrayList<BaseDictData>();
		}
		groups.add(newGroup);
	}

	protected void WriteInfo(DataOutputStream writer) throws IOException{
		writer.writeByte(itemsFlag);
		if(groups != null){
			writer.writeByte(groups.size());
			for(BaseDictData group : groups){
				group.WriteInfo(writer);
			}
		}
		else{
			writer.writeByte(0);
		}
	}
	
	protected void ReadInfo(BufferReader reader){
		itemsFlag = reader.ReadByte();
		int groupsSize = reader.ReadByte();
		for(int i=0; i<groupsSize; ++i){
			BaseDictData newGroup = new BaseDictData(MaxItemSize);
			newGroup.ReadInfo(reader);
			AddGroup(newGroup);
		}
	}
	
	protected String PackContent(int level){
		String rev = "";
		String separator = "@" + level;
		if(items != null){
			for(String item : items){
				if(item != null){
					rev += (item + separator);
				}
			}		
		}
		
		if(groups != null){
			for(BaseDictData group : groups){
				rev += (group.PackContent(level+1) + separator);
			}
		}
		return rev;
	}
	
	protected void ReadContent(String s, int level){
		String separator = "@" + level;
		String members[] = s.split(separator);
		int itemCount = 0;
		int curMember = 0;
		int flag = itemsFlag;
		for(int i=0x01; flag!=0; i=i<<1, ++itemCount){
			if((flag & i) != 0){
				flag &= ~i;
				items[itemCount] = members[curMember++];
			}
		}
		if(groups != null){
			for(BaseDictData group : groups){
				group.ReadContent(members[curMember++], level+1);
			}
		}
	}
	
	public void Write(DataOutputStream writer) throws IOException{
		WriteInfo(writer);
		writer.writeUTF(PackContent(0));
	}
	
	public void Read(BufferReader reader){
		ReadInfo(reader);
		ReadContent(reader.ReadString(), 0);
	}
}
